package com.bit.forum.interceptor;

import com.bit.forum.config.APPConfig;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;


@Component
public class LoginInterceptor implements HandlerInterceptor {

    @Value("${bit-forum.login.url}")
    private String defaultURL;
    /**
     * 前置处理
     * true:继续流程
     * false:流程中断
     */
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //获取session
        HttpSession session = request.getSession(false);
        if (session != null && session.getAttribute(APPConfig.USER_SESSION) != null){
            //用户已登录
            return true;
        }
        //校验url是否正确,拼装
        if (!defaultURL.startsWith("/")){
            defaultURL = "/"+defaultURL;
        }
        //校验不通过,跳转到登录页面
        response.sendRedirect(defaultURL);
        //中断流程
        return false;
    }
}
